package com.xhs.hawaii.framework.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author tangchuang
 * @version 1.0
 * @since 2018/1/20
 */
@Component
@Slf4j
public class ZookeeperHelper {

    @Value("${zk.hosts}")
    private String hosts;

    private int sessionTimeout = 10000;

    private int connectionTimeout = 10000;

    private static CuratorFramework zkClient;


    @PostConstruct
    public void init() {
        if (null == zkClient) {
            synchronized (ZookeeperHelper.class) {
                if (null == zkClient) {
                    log.info("=============== start to  connect zk host " + hosts + "...=================");
                    zkClient = CuratorFrameworkFactory.builder().connectString(hosts).sessionTimeoutMs(sessionTimeout)
                            .connectionTimeoutMs(connectionTimeout).canBeReadOnly(true)
                            .retryPolicy(new ExponentialBackoffRetry(1000, 100)).defaultData(null)
                            .build();
                    zkClient.start();
                }
            }
        }
    }

    public CuratorFramework getZkClient() {
        return zkClient;
    }


}
